package com.fucking.great.context.single;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.fucking.great.context.util.SingleUtil;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 单例化,所有定义在 <code>com.fucking.great.context.single.resource</code> 包下
 * 类中上有@javax.annotation.Resource的类。
 * 生成的key名 {@link com.fucking.great.context.util.SingleUtil#classToKey}
 */
public class ResourceSingleFactory implements SingleFactory {
    public static final Log log = LogFactory.get();

    @Override
    public Map<String,Object> getNeedRegsigAllBean(Map<String,Object> storageCenter) {
        //
        Map<String, Object> map = new HashMap<>();
        String packageName = "com.fucking.great.context.single.resource";

        scanPackagePutBean(packageName,map);
        //
        return map;
    }


    /**
     * 扫描包，并put到map中。
     * @param packageName
     * @param map
     */
    private void scanPackagePutBean(String packageName, Map<String, Object> map) {
        log.info("Resource扫描工厂,扫描包[{}],下面的类,并实例化",packageName);
        //
        Set<Class<?>> resourceClasses = ClassUtil.scanPackageByAnnotation(
                packageName, Resource.class);
        //
        resourceClasses.forEach(cla ->{
            try {
                // new
                Object instance = cla.newInstance();
                // 不依赖.

                // put
                String classToKey = SingleUtil.classToKey(cla);
                map.putIfAbsent(classToKey,instance);
                log.debug("通过@Resource单例化[{}]成功",cla);
            } catch (Exception e) {
                log.warn(e,"扫描实例化[{}]类出现异常，请核查是否有构造函数",cla);
            }
        });
    }


}
